package com.cci.kangdao.wechatOrder.service.impl;

import com.cci.kangdao.dao.UserTDao;
import com.cci.kangdao.dao.WorkOrderTDao;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dao.model.WorkOrderT;
import com.cci.kangdao.utilTool.JsonUtils;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import com.cci.kangdao.wechatOrder.dao.WeChatNotifyRecordTDao;
import com.cci.kangdao.wechatOrder.dao.WeChatUserRelationTDao;
import com.cci.kangdao.wechatOrder.model.WeChatNotifyRecordT;
import com.cci.kangdao.wechatOrder.model.WeChatUserRelationT;
import com.cci.kangdao.wechatOrder.model.wx.MessageData;
import com.cci.kangdao.wechatOrder.model.wx.PushMessage;
import com.cci.kangdao.wechatOrder.model.wx.WxResult;
import com.cci.kangdao.wechatOrder.service.IOrderPushMessageService;
import com.cci.kangdao.wechatOrder.service.IWxChatSdkService;
import com.cci.kangdao.wechatOrder.util.wxsdk.WxUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @description: 订单消息推送服务实现类
 * @author: zyf
 * @create: 2021-03-12
 */
@Service
public class OrderPushMessageServiceImpl implements IOrderPushMessageService {
    private Logger log = Logger.getLogger(this.getClass().getName());
    /**
     * 微信消息推送记录
     */
    @Resource
    private WeChatNotifyRecordTDao weChatNotifyRecordTDao;

    @Resource
    private IWxChatSdkService wxChatSdkService;

    @Resource
    private WorkOrderTDao workOrderTDao;
    @Resource
    private WeChatUserRelationTDao relationTDao;
    @Resource
    private UserTDao userTDao;


    @Override
    public void sendOrderMessage(Long orderId, String url, String firstData, String keyword1, String keyWord2, String keyWord3,String keyWord4, String remark) throws Exception {
        log.info("进入推送公众号消息工具类sendOrderMessage，参数：orderId" + orderId + ",url" + url + ",firstData" + firstData + ",keyword1" + keyword1
                + ",keyWord2" + keyWord2 + ",keyWord3" + keyWord3 + ",keyWord4" + keyWord4 + ",remark" + remark);
        WorkOrderT workOrderT =workOrderTDao.getWorkOrderByOrderId(orderId);
        if (workOrderT == null){
            //throw new NotCheckException("找不到工单数据");
            log.error("找不到工单数据");
            return;
        }
        UserT userT = userTDao.checkUserByNameOrPhone(workOrderT.getCustomerPhone());
        if (userT == null){
            //throw new NotCheckException("找不到用户信息");
            log.error("找不到用户信息");
            return;
        }
        WeChatUserRelationT weChatUserRelationT = relationTDao.selectByUserId(userT.getId(),(long)workOrderT.getOrderChannel());
        if (weChatUserRelationT == null){
            //throw new NotCheckException("找不到绑定微信用户ID");
            log.error("找不到绑定微信用户ID");
            return;
        }

        //创建微信消息类型
        String templateId = WxUtils.getWxTemplateId((long)workOrderT.getOrderChannel(),null);
        PushMessage pm = new PushMessage();
        pm.setTouser(weChatUserRelationT.getOpenID());
        pm.setTemplate_id(templateId);
        pm.setUrl(url);
        MessageData messageData= new MessageData();
        messageData.setFirst(firstData);
        messageData.setKeyword1(keyword1);
        messageData.setKeyword2(keyWord2);
        messageData.setKeyword3(keyWord3);
        messageData.setKeyword4(keyWord4);
        messageData.setRemark(remark);
        pm.setData(messageData);
        //进行消息推送处理
        WxResult result =  wxChatSdkService.wxPushMessage((long)workOrderT.getOrderChannel(),pm);
        if (null != result) {
            log.info("公众号消息推送成功，返回结果为：信息：" + result.getErrmsg() + ",code:" + result.getErrcode());
        } else {
            log.error("公众号消息推送失败，返回结果为空");
        }

        int flag = weChatNotifyRecordTDao.insert(getNotifyRecord(orderId,workOrderT.getCustomerId(),templateId,weChatUserRelationT.getOpenID(),pm,result));

        if (flag ==0){
            //throw new NotCheckException("插入微信推送日志失败");
            log.error("插入微信推送日志失败");
            return;
        }
    }

    private WeChatNotifyRecordT getNotifyRecord(Long orderId,Long receiverId,String templateId,String openId,PushMessage pm,WxResult result){
        WeChatNotifyRecordT recordT = new WeChatNotifyRecordT();
        recordT.setSendType(1);
        recordT.setToUser(openId);
        recordT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
        recordT.setReceiverId(receiverId);
        recordT.setSendTime(LocalTimeUtil.getRealCurrentTime());
        recordT.setContent(JsonUtils.toJsonString(pm));
        recordT.setOrderId(orderId);
        recordT.setCreator(-1L);
        recordT.setExceptionInfo(null != result ? result.getErrmsg() : "");
        recordT.setStatus(null != result ? 0 == result.getErrcode() ? 0 : 1 : 0);
        recordT.setTemplateId(templateId);
        return recordT;
    }
}
